package com.wtwd.device.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.xiaoymin.knife4j.annotations.DynamicParameter;
import com.github.xiaoymin.knife4j.annotations.DynamicParameters;
import com.wtwd.device.constant.Constants;
import com.wtwd.device.constant.RespCode;
import com.wtwd.device.model.entity.DeviceSetting;
import com.wtwd.device.model.entity.SysRole;
import com.wtwd.device.model.entity.SysUser;
import com.wtwd.device.model.vo.RespEntity;
import com.wtwd.device.service.DeviceSettingService;
import com.wtwd.device.service.RedisService;
import com.wtwd.device.service.SysRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@Api(tags = "设备管理")
@RestController
@RequestMapping("/setting")
public class DeviceSettingController {
    private static final Logger logger = LoggerFactory.getLogger(DeviceSettingController.class);
    @Value("${product.image}")
    private String imgPlace;
    @Value("${file.http}")
    private String fileHttp;
    @Value("${file.path}")
    private String filePath;
    @Autowired
    private DeviceSettingService deviceSettingService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private SysRoleService sysRoleService;

    /**
     * 查询设备设置列表
     *
     * @param data
     * @return
     */
    @ApiOperation("查询设备设置列表")
    @DynamicParameters(name = "getDeviceSettingList", properties = {
            @DynamicParameter(name = "curPage", value = "当前页", dataTypeClass = Integer.class, required = true)
            , @DynamicParameter(name = "watchId", value = "手表id", dataTypeClass = String.class, required = true)
            , @DynamicParameter(name = "pageSize", value = "页面大小", dataTypeClass = Integer.class, required = true)
    })
    @PutMapping("/getDeviceSettingList")
    public RespEntity getDeviceSettingList(@RequestBody JSONObject data, HttpServletRequest request) {
        logger.info("getDeviceSettingList: data = {}" + data.toString());
        //获取用户id和角色类型
        List<Object> list = getUserIdAndRoleType(request);
        Long userId = (Long) list.get(0);
        if (userId == 0) {
            return new RespEntity(RespCode.TOKEN_UNAUTHORIZED);
        }
        Integer roleType = (Integer) list.get(1);
        if (roleType == Constants.SYS_USER_ROLE_TYPE_ADMIN) {
            //管理员可以查看全部
            userId = null;
        }
        String watchId = (String) data.get("watchId");
        Integer curPage = (Integer) data.get("curPage");
        Integer pageSize = (Integer) data.get("pageSize");
        Map<String, Object> settingList = deviceSettingService.getDeviceSettingListByWatchId(watchId, userId, curPage, pageSize);
        return new RespEntity(RespCode.SUCCESS, settingList);
    }

    /**
     * 上传产品缩略图
     *
     * @param file
     * @param request
     * @return
     */
    @ApiOperation("上传产品缩略图")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "文件", required = true, dataTypeClass = MultipartFile.class)
    })
    @PostMapping("/uploadImage")
    public RespEntity uploadImage(@RequestBody MultipartFile file, HttpServletRequest request) {
        logger.info("/uploadImage");
        String path = filePath.concat(imgPlace);
        File saveFile = new File(path);
        if (!saveFile.exists()) {
            //文件不存在则创建一个
            saveFile.mkdir();
        }
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString().concat(originalFilename);
        File dest = new File(path.concat(fileName));
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            return new RespEntity(RespCode.FAILED);
        }
        return new RespEntity(RespCode.SUCCESS, fileName);
    }

    /**
     * 添加手表
     *
     * @param data
     * @param request
     * @return
     */
    @ApiOperation("添加手表")
    @DynamicParameters(name = "addWatch", properties = {
            @DynamicParameter(name = "watchId", value = "手表id", dataTypeClass = String.class, required = true)
            , @DynamicParameter(name = "imgName", value = "图片名称", dataTypeClass = String.class, required = true)
    })
    @PostMapping("/addWatch")
    public RespEntity addWatch(@RequestBody DeviceSetting data, HttpServletRequest request) {
        logger.info("addWatch: data = {}", data.toString());
        //获取用户id
        //获取用户id和角色类型
        List<Object> list = getUserIdAndRoleType(request);
        Long userId = (Long) list.get(0);
        if (userId == 0) {
            return new RespEntity(RespCode.TOKEN_UNAUTHORIZED);
        }
        //判断手表id是否重复
        List<DeviceSetting> settingList = deviceSettingService.getDeviceListByWatchId(data.getWatchId());
        if (settingList != null && settingList.size() == 0) {
            data.setUserId(userId);
            data.setUpdateTime(System.currentTimeMillis());
            Integer i = deviceSettingService.addDeviceSetting(data);
            return new RespEntity(i > 0 ? RespCode.SUCCESS : RespCode.FAILED);
        }
        return new RespEntity(RespCode.WATCH_ID_REPEAT);
    }

    /**
     * 编辑手表
     *
     * @param data
     * @param request
     * @return
     */
    @ApiOperation("添加手表")
    @DynamicParameters(name = "modifyWatch", properties = {
            @DynamicParameter(name = "id", value = "手表id主键，唯一标识", dataTypeClass = Integer.class, required = true)
            ,@DynamicParameter(name = "watchId", value = "手表id", dataTypeClass = String.class, required = true)
            , @DynamicParameter(name = "imgName", value = "图片名称", dataTypeClass = String.class, required = true)
    })
    @PutMapping("/modifyWatch")
    public RespEntity modifyWatch(@RequestBody DeviceSetting data, HttpServletRequest request) {
        logger.info("modifyWatch: data = {}", data.toString());
        //获取用户id和角色类型
        List<Object> list = getUserIdAndRoleType(request);
        Long userId = (Long) list.get(0);
        if (userId == 0) {
            return new RespEntity(RespCode.TOKEN_UNAUTHORIZED);
        }
        Integer roleType = (Integer) list.get(1);
        //判断是否有权操作
        boolean b = veryIFCanDo(userId, data.getWatchId(), roleType);
        DeviceSetting deviceSetting = deviceSettingService.getDeviceSettingById(data.getId());
        if (deviceSettingService.authWatchIdIsRelevancy(deviceSetting,data.getWatchId())){
            return new RespEntity(RespCode.WATCH_ID_IS_EXIST_RELEVANCY);
        }
        if (b) {
            //判断手表id是否重复
            List<DeviceSetting> settingList = deviceSettingService.getDeviceListByWatchId(data.getWatchId());
            if (settingList != null && settingList.size() == 0 || (settingList != null && settingList.get(0).getId() == data.getId())) {
                data.setUpdateTime(System.currentTimeMillis());
                Integer i = deviceSettingService.modifyDeviceSettingByWatchId(data);
                return new RespEntity(i > 0 ? RespCode.SUCCESS : RespCode.FAILED);
            }
            return new RespEntity(RespCode.WATCH_ID_REPEAT);
        }
        return new RespEntity(RespCode.NO_RIGHT_OPERATION);
    }

    /**
     * 判断该用户是否有权限操作该手表设置
     *
     * @param userId
     * @param watchId
     * @return
     */
    public boolean veryIFCanDo(Long userId, String watchId, Integer roleType) {
        if (roleType == Constants.SYS_USER_ROLE_TYPE_ADMIN || roleType == Constants.SYS_USER_ROLE_TYPE_OPERATOR) {
            return true;
        }
        //根据用户id查找该用户所属客户下的所有手表id
        List<String> watchIdList = deviceSettingService.getWatchIdByUserId(userId);
        boolean b = watchIdList.contains(watchId);
        return b;
    }


    /**
     * 获取用户id和角色类型
     *
     * @return
     */
    public List<Object> getUserIdAndRoleType(HttpServletRequest request) {
        String token = request.getHeader("Manager-token");
        Map<String, Object> map = redisService.getUserInfoByToken(token);
        if (map == null) {
            return null;
        }
        String str = (String) map.get("user");
        SysUser user = JSONObject.parseObject(str, SysUser.class);
        //根据角色id获取角色类型
        SysRole sysRole = sysRoleService.getSysRoleByRoleId(user.getRoleId());
        Long userId = user.getUserId();
        Integer roleType = sysRole.getRoleType();
        List<Object> list = new ArrayList<>();
        list.add(0, userId);
        list.add(1, roleType);
       /* List<Object> list = new ArrayList<>();
        list.add(0,4l);
        list.add(1,1);*/
        return list;
    }


}
